﻿using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Super
{
	[ExecuteInEditMode]
	[RequireComponent(typeof(Image))]
	public class AsyncImage : MonoBehaviour
	{
		private Image imageComponent;
		public Image ImageComponent
		{
			get
			{
				if (imageComponent == null)
					imageComponent = GetComponent<Image>();
				return imageComponent;
			}
		}

		[SerializeField]
		private Sprite imageSprite;
		private Sprite oldImageSprite;

		public string imageAddr = "";
		private string oldImageAddr;

		public void OnValidate()
		{
			bool isChangeSprite = imageSprite != oldImageSprite;
			bool isChangeAddr = imageAddr != oldImageAddr;
			bool isClearSprite = imageSprite == null;
			bool isAssetExist = AssetUtil.AssetExist(imageAddr);
			bool isClearAddr = string.IsNullOrEmpty(imageAddr);

#if UNITY_EDITOR
			if (isChangeSprite && !isClearSprite)
			{
				OnSetImageSprite();
			}
			else if (isChangeAddr && !isClearAddr && isAssetExist)
			{
				OnSetImageAddr();
			}
			else if ((isChangeAddr && isClearAddr) || (isChangeSprite && isClearSprite))
			{
				OnClear();
			}
#endif
		}

		private void OnSetImageSprite()
		{
			oldImageSprite = imageSprite;
			ImageComponent.sprite = imageSprite;
#if UNITY_EDITOR
			imageAddr = AssetDatabase.GetAssetPath(imageSprite);
			oldImageAddr = imageAddr;
			if (!AssetUtil.EditorAddrExist(imageAddr))
			{
				AssetUtil.CreateOrMoveEntry(ValueSettingSO.Ins.spritAGroup, imageAddr);
			}
#endif
		}
		private void OnSetImageAddr()
		{
			oldImageAddr = imageAddr;
			Sprite sprite = AssetUtil.LoadAsset<Sprite>(imageAddr);
			imageSprite = sprite;
			oldImageSprite = imageSprite;
			ImageComponent.sprite = imageSprite;
#if UNITY_EDITOR
			if (!AssetUtil.EditorAddrExist(imageAddr))
			{
				AssetUtil.CreateOrMoveEntry(ValueSettingSO.Ins.spritAGroup, imageAddr);
			}
#endif
		}
		private void OnClear()
		{
			imageAddr = "";
			oldImageAddr = imageAddr;
			imageSprite = null;
			oldImageSprite = imageSprite;
			ImageComponent.sprite = imageSprite;
		}

		public void SetImageAddr(string imageAddr)
		{
			this.imageAddr = imageAddr;
			OnSetImageAddr();
		}

		public void SetImageSprite(Sprite imageSprite)
		{
			this.imageSprite = imageSprite;
			OnSetImageSprite();
		}
	}
}

